<?php
/*
  $Id$

  osCommerce, Open Source E-Commerce Solutions
  http://www.oscommerce.com

  Copyright (c) 2010 osCommerce

  Released under the GNU General Public License
  Author : Dong Hong
  Email  : donghp712@gmail.com
*/

  class bm_brands {
    var $code = 'bm_brands';
    var $group = 'boxes';
    var $title;
    var $description;
    var $sort_order;
    var $enabled = false;
    var $manufactures;
	
	
    function bm_brands() {
      $this->title = MODULE_BOXES_BRANDS_TITLE;
      $this->description = MODULE_BOXES_BRANDS_DESCRIPTION;

      if ( defined('MODULE_BOXES_BRANDS_STATUS') ) {
        $this->sort_order = MODULE_BOXES_BRANDS_SORT_ORDER;
        $this->enabled = (MODULE_BOXES_BRANDS_STATUS == 'True');

        $this->group = ((MODULE_BOXES_BRANDS_CONTENT_PLACEMENT == 'Left Column') ? 'boxes_column_left' : 'boxes_column_right');		
      }
    }
   
    function get_all() {
        global $cPath_array;

        $id = $cPath_array[count($cPath_array) - 1];

       //---------Edit By DongHP ---------------
	   //---------Email : donghp712@gmail.com ------------
	   //--brands are sorted by total products viewed ----
	   
      //---------------------Modify and Added by NamHai 12/07/2012-------------------------- 
        /*  $sql = "select distinct m.manufacturers_id,SUM( pd.products_viewed ) AS total_views ";
      
	   $sql .= " from " . TABLE_PRODUCTS . " p left join " . TABLE_MANUFACTURERS . " m using(manufacturers_id)";
       $sql .= " , " . TABLE_PRODUCTS_DESCRIPTION . " pd, " . TABLE_CATEGORIES . " c, " . TABLE_PRODUCTS_TO_CATEGORIES . " p2c";
       $sql .= " where p.products_status = '1' and p.products_id = pd.products_id and p.products_id = p2c.products_id and p2c.categories_id = c.categories_id ";  	   	   
	  // if ($id && $id>0) $sql .="and c.categories_id= $id"; 
	   $sql .=" GROUP BY p.manufacturers_id ORDER BY total_views DESC";	  */  	

        $sql = "select distinct p.products_id, pd.products_name, SUM( pd.products_viewed ) AS total_views ";   
        $sql .= " from " . TABLE_PRODUCTS . " p ";
        $sql .= " , " . TABLE_PRODUCTS_DESCRIPTION . " pd, " . TABLE_CATEGORIES . " c, " . TABLE_PRODUCTS_TO_CATEGORIES . " p2c";
        $sql .= " where p.products_status = '1' and p.products_id = pd.products_id ";
        $sql .=" GROUP BY p.products_id ORDER BY total_views DESC";
	//---------------------------End by NamHai 12/07/2012---------------------------------   	   
	   
       $exit_m = array();
       
	   $m_id_query = mysql_query($sql);
       
	   if ($m_id_query  && tep_db_num_rows($m_id_query) > 0) //add by donghp
	   {
		   while ($manu_id = tep_db_fetch_array($m_id_query)) {
		   
			//---------------------Modify and Added by NamHai 12/07/2012-------------------------------
		   		/* $exit_m[] = $manu_id['manufacturers_id'];
				$m_query = mysql_query("select manufacturers_name,manufacturers_id from " . TABLE_MANUFACTURERS . " where manufacturers_id = " . $manu_id['manufacturers_id'] . " order by manufacturers_id ASC");
				 */
		   		/*$exit_m[] = $manu_id['products_id'];
		   		$m_query = mysql_query("select pd.products_name, p.products_id from " . TABLE_PRODUCTS . "  p right join " . TABLE_PRODUCTS_DESCRIPTION . " pd using(products_id) where p.products_id = " . $manu_id['products_id'] . " order by p.products_id ASC");*/
		   	
		   		$exit_m[] = $manu_id['products_id'];
		   		$m_query = mysql_query("select products_model, products_id from " . TABLE_PRODUCTS . " where products_id = " . $manu_id['products_id'] . " order by products_id ASC");

		   		//echo "select products_name, products_id from " . TABLE_PRODUCTS_DESCRIPTION . " where products_id = " . $manu_id['products_id'] . " order by products_id ASC";
		   		//die();
		   	//--------------------------------End by NamHai 12/07/2012---------------------------------
				
				while ($manufacture = tep_db_fetch_array($m_query)) {
					$this->manufactures[] = $manufacture;
				}
			  }
			   return $this->manufactures;
	   }
		else { return NULL; }
      }
	

    function get_top30() {
        global $cPath_array;

        $id = $cPath_array[count($cPath_array) - 1];

       //---------Edit By DongHP ---------------
	   //---------Email : donghp712@gmail.com ------------
	   //--brands are sorted by total products viewed ----
       $sql = "select distinct m.manufacturers_id,SUM( pd.products_viewed ) AS total_views ";
      
	   $sql .= " from " . TABLE_PRODUCTS . " p left join " . TABLE_MANUFACTURERS . " m using(manufacturers_id)";
       $sql .= " , " . TABLE_PRODUCTS_DESCRIPTION . " pd, " . TABLE_CATEGORIES . " c, " . TABLE_PRODUCTS_TO_CATEGORIES . " p2c";
       $sql .= " where p.products_status = '1' and p.products_id = pd.products_id and p.products_id = p2c.products_id and p2c.categories_id = c.categories_id ";
	   	   	   
	  // if ($id && $id>0) $sql .="and c.categories_id= $id"; 
	   
	   $sql .=" GROUP BY p.manufacturers_id ORDER BY total_views DESC  LIMIT 0 , 30 ";	   	   
	   
       $exit_m = array();
       
	   $m_id_query = mysql_query($sql);
       
	   if ($m_id_query  && tep_db_num_rows($m_id_query) > 0) //add by donghp
	   {
		   while ($manu_id = tep_db_fetch_array($m_id_query)) {
				$exit_m[] = $manu_id['manufacturers_id'];
				$m_query = mysql_query("select manufacturers_name,manufacturers_id from " . TABLE_MANUFACTURERS . " where manufacturers_id = " . $manu_id['manufacturers_id'] . " order by manufacturers_id ASC");
				while ($manufacture = tep_db_fetch_array($m_query)) {
					$this->manufactures[] = $manufacture;
				}
			  }
			   return $this->manufactures;
	   }
		else { return NULL; }
      }
	
	
	function get_brand_other()
	{
	 global $cPath_array;

        $id = $cPath_array[count($cPath_array) - 1];

       //---------By DongHP ---------------ORD('a')= 97 ORD ('z')=122
	   //---------Email : donghp712@gmail.com ------------
	   //--brands are sorted by total products viewed ----
      $sql = "select distinct m.manufacturers_id,m.manufacturers_name,SUM( pd.products_viewed ) AS total_views ";
      
	   $sql .= " from " . TABLE_PRODUCTS . " p left join " . TABLE_MANUFACTURERS . " m using(manufacturers_id)";
       $sql .= " , " . TABLE_PRODUCTS_DESCRIPTION . " pd, " . TABLE_CATEGORIES . " c, " . TABLE_PRODUCTS_TO_CATEGORIES . " p2c";
       $sql .= " where p.products_status = '1' and p.products_id = pd.products_id and p.products_id = p2c.products_id and p2c.categories_id = c.categories_id and ( LEFT( LOWER(m.manufacturers_name), 1)  < 'a'
or LEFT( LOWER(m.manufacturers_name), 1)  > 'z' ) ";
	   	   	   
	 //  if ($id && $id>0) $sql .=" and c.categories_id= $id"; 
	   
	   $sql .=" GROUP BY p.manufacturers_id ORDER BY total_views DESC";	   	   
	   
	 //  echo "Orther : ".$sql."<br>";
	   
       $exit_m = array();
       
	   $m_id_query = mysql_query($sql);
       
	   $manuf = array();
		 
	   if ($m_id_query   && tep_db_num_rows($m_id_query) >= 1) //add by donghp
	   {		  		   
		   while ($manu_id = tep_db_fetch_array($m_id_query)) {
			  
			   	$exit_m[] = $manu_id['manufacturers_id'];
				$m_query = mysql_query("select manufacturers_name,manufacturers_id from " . TABLE_MANUFACTURERS . " where manufacturers_id = " . $manu_id['manufacturers_id'] . " order by manufacturers_id ASC");
				while ($manufacture = tep_db_fetch_array($m_query)) {
					$manuf[] = $manufacture;
				}
			  }
			   return $manuf;
	    }
	    else { return NULL; }
	}
	
	function get_brand_abc($ch) {
        global $cPath_array;

        $id = $cPath_array[count($cPath_array) - 1];

       //---------By DongHP ------------------------------
	   //---------Email : donghp712@gmail.com ------------
	   //--brands are sorted by total products viewed ----
      $sql = "select distinct m.manufacturers_id,m.manufacturers_name,SUM( pd.products_viewed ) AS total_views ";
      
	   $sql .= " from " . TABLE_PRODUCTS . " p left join " . TABLE_MANUFACTURERS . " m using(manufacturers_id)";
       $sql .= " , " . TABLE_PRODUCTS_DESCRIPTION . " pd, " . TABLE_CATEGORIES . " c, " . TABLE_PRODUCTS_TO_CATEGORIES . " p2c";
       $sql .= " where p.products_status = '1' and p.products_id = pd.products_id and p.products_id = p2c.products_id and p2c.categories_id = c.categories_id and LEFT( LOWER(m.manufacturers_name), 1) = '".$ch."'";
	   	   	   
	  // if ($id && $id>0) $sql .=" and c.categories_id= $id"; 
	   
	   $sql .=" GROUP BY p.manufacturers_id ORDER BY m.manufacturers_name DESC";	   	   
	   
	  // echo "<b>".$ch." = ".$sql."</b><br>";
	   
       $exit_m = array();
       
	   $m_id_query = mysql_query($sql);
       
	   $manuf = array();
		 
	   if ($m_id_query   && tep_db_num_rows($m_id_query) >= 1) //add by donghp
	   {		  		   
		   while ($manu_id = tep_db_fetch_array($m_id_query)) {
			  
			   	$exit_m[] = $manu_id['manufacturers_id'];
				$m_query = mysql_query("select manufacturers_name,manufacturers_id from " . TABLE_MANUFACTURERS . " where manufacturers_id = " . $manu_id['manufacturers_id'] . " order by manufacturers_id ASC");
				while ($manufacture = tep_db_fetch_array($m_query)) {
					$manuf[] = $manufacture;
				}
			  }
			   return $manuf;
	    }
	    else { return NULL; }
      }
	  
	function products_in_manu($category_id, $manu_id) {
		
		$q = "select count(*) as total from " . TABLE_PRODUCTS . " p, " . TABLE_PRODUCTS_TO_CATEGORIES . " p2c where p.products_id = p2c.products_id and p.products_status = '1' and p2c.categories_id = '" . (int) $category_id . "' and p.manufacturers_id ='" . $manu_id . "'";
		
        $products_count = 0;
        
        $products_query = tep_db_query($q);

        $products = tep_db_fetch_array($products_query);
        $products_count += $products['total'];

        /*if ($products_count) {
            return '(' . $products_count . ')';
        }*/
        return $products_count;
    }
	
	function gen_pagnav_abc()
	{
	   $s='<div class="srSprite spr_header hdr"><div class="pagn" id="ultabs">';
	   $s.='<span class="pagnLead notBold">Viewing:</span>';
	   $s.='<span class="pagnCur"><a href="#tab1">Top Brands</a></span>';
	   $s.='<span class="pagnLink"><a href="#tab2">#</a></span>';
	   
	   for ($ch=ord('A');$ch<=ord('Z');$ch++)
		 { 
		   $id= $ch+3-ord('A');
		   $s.='<span class="pagnLink"><a href="#tab'.$id.'">'.chr($ch).'</a></span>';								
		 }
	
	   $s.='<span class="pagnLink"><a href="javascript:void(0);" onclick="get_brand(\'View All\',0);">View All</a></span>';
		 
	   $s.='</div></div>';
			  
	 return $s;	
	}

	function column_li($name,$id,$n)
	{
		return
	'<li><a href="javascript:void(0);" onClick="get_brand(\''.$name.'\','.$id.');">
    <span class="refinementLink">'.$name.'</span><span class="narrowValue">&nbsp;('.$n.')</span></a></li>';
	}
	
	function gen_tab_brand($menu,$id)
	{
	 	// var_dump($menu);
		// echo "<br>-----------------------------------------------<br>";
		 
		 $n = count($menu);
		 if ($n < 1)   return '<div id="tab'.$id.'" class="tab_content" ></div>';
	//	 echo "<br>n = $n <br>";
		 
		 $m = (int)(($n+1)/3); if ($m <1 ) $m =1;

		 $col1='<ul class="column">';
		
		for ($k=0;$k<$m;$k++) //cot 1
		   {
			   $count_p= tep_count_products_in_manu($menu[$k]['manufacturers_id'], true);
			   $col1.=$this->column_li($menu[$k]['manufacturers_name'],$menu[$k]['manufacturers_id'],$count_p);
		   }
		
		$col1.='</ul>';
		
		$col2='<ul class="column">';
		
		for ($k=$m;$k<2*$m;$k++) //cot 1
		   {
			 if ($k<$n)
			  {
			    $count_p= tep_count_products_in_manu($menu[$k]['manufacturers_id'], true);
			    $col2.=$this->column_li($menu[$k]['manufacturers_name'],$menu[$k]['manufacturers_id'],$count_p);
			  }
		   }
		
		$col2.='</ul>';
		
		$col3='<ul class="column">';
		
		for ($k=2*$m;$k<$n;$k++) //cot 1
		   { 
		     if ($k<$n)
			   {
			     $count_p= tep_count_products_in_manu($menu[$k]['manufacturers_id'], true);
			     $col3.=$this->column_li($menu[$k]['manufacturers_name'],$menu[$k]['manufacturers_id'],$count_p);
			   }
		   }
		
		$col3.='</ul>';
      
	 
	   return '<div id="tab'.$id.'" class="tab_content">
				    <div class="c3_ref refList">'.$col1.$col2.$col3.
			       '</div>
                 </div>';
	}
	
	
	//----------------------Added by NamHai 12/07/2012------------------------
	function gen_tab_view_all_product($menu,$id)
	{	
	
		for ($h=0;$h<count($menu);$h++)
		{
			if($menu[$h]['products_model']=="");
			unset($menu[$h]);
		}
		
		$menu = array_values($menu);
		
		$n = count($menu);
		
		
		if ($n < 1)   return '<div id="tab'.$id.'" class="tab_content" ></div>';
			
		$m = (int)(($n+1)/3); if ($m <1 ) $m =1;
	
		$col1='<ul class="column">';
	
		for ($k=0;$k<$m;$k++)
		{
			$count_p= tep_count_products_in_manu($menu[$k]['products_id'], true);
			$col1.=$this->column_li($menu[$k]['products_model'],$menu[$k]['products_id'],$count_p);
		}
	
		$col1.='</ul>';
	
		$col2='<ul class="column">';
	
		for ($k=$m;$k<2*$m;$k++)
		{
			if ($k<$n)
			{
				$count_p= tep_count_products_in_manu($menu[$k]['products_id'], true);
				$col2.=$this->column_li($menu[$k]['products_model'],$menu[$k]['products_id'],$count_p);
			}
		}
	
		$col2.='</ul>';
	
		$col3='<ul class="column">';
	
		for ($k=2*$m;$k<$n;$k++)
		{
			if ($k<$n)
			{
				$count_p= tep_count_products_in_manu($menu[$k]['products_id'], true);
				$col3.=$this->column_li($menu[$k]['products_model'],$menu[$k]['products_id'],$count_p);
			}
		}
	
		$col3.='</ul>';
	
	
		return '<div id="tab'.$id.'" class="tab_content">
		<div class="c3_ref refList">'.$col1.$col2.$col3.
		'</div>
		</div>';
	}
	//--------------------------End by NamHai 2012--------------------------
	
	
	
    function getData() {
      global $HTTP_GET_VARS, $oscTemplate,  $cPath_array,$current_category_id,$where_str; // by donghp
		
	//if (empty($cPath_array)) return '';
		
     $id = $cPath_array[count($cPath_array) - 1];

     $data = '';

     $i = 0;
     $menu = array(); $menu2 = array();                                                 
	  
 $content= tep_draw_form('brands', tep_href_link(FILENAME_DEFAULT, '', 'NONSSL', false), 'get').'<input type="hidden" name="manufacturers_id" id = "manufacturers_id" value="'.(isset($HTTP_GET_VARS['manufacturers_id']) ? $HTTP_GET_VARS['manufacturers_id'] : '').'" />'. tep_hide_session_id() . '</form>

 <div id="nav">
	<div id="navul">
		<div id="login">
			<a id="login-trigger" href="javascript:void(0);">Please select <span>&#x25BC;</span>
			</a>
			<div id="login-content">'.$this->gen_pagnav_abc();

	 //-------------------------Top Brands ------------------------------------------------          
	 $menu = $this->get_top30();
	  
     if (is_array($menu) && count($menu)) {
		 
		  $content.= $this->gen_tab_brand($menu,1);
       }  

	  //-------------End top brand---------------------------------------------------------
	   
	  $menu2= $this->get_brand_other();
	  
	   if (is_array($menu2) && count($menu2)) {
		 
		  $content.= $this->gen_tab_brand($menu2,2);
       }  
	  
	  for ($ch = ord('a');$ch<=ord('z');$ch++)
		 {
			
			 if (is_array($menu) && count($menu)) {				 
			      				  
				  $brand = $this->get_brand_abc(chr($ch));

				  $content.= $this->gen_tab_brand($brand,$ch+3-ord('a'));
			 }				
       }  
	  //--------------------------Get All view tab -----------------------------
	    
	   //---------------------Modify by NamHai 12/07/2012-----------------------
	   $menu2 = $this->get_all();
	   
	   if (is_array($menu2) && count($menu2)) {
		 
		  $content.= $this->gen_tab_view_all_product($menu2,100); // view all
       }  
	
     //--------------------------End by NamHai 12/07/2012-----------------------
	  $content.=$this->gen_pagnav_abc();		 			
	  
	 $content.='</div>
        </div>
	</div> 
</div>';
    //---------------------Add AVG.Customer reviews ---------------------------------------
            
            // <div class="star_rating" id="4_2"></div><span class="reviews"> & Up </span> 
			// <div class="avgrating">AAAAAAAA</div>  
      /*$content.='
	  <div id ="avg"><div class="title">Avg. Customer Review</div>
	 <div class="avgrating"><div class="star_rating" id="4_2"></div><span class="reviews"> & Up (<span class="BAvg4">'.tep_count_avg_rating(4,$current_category_id).'</span>)</span></div>
	 <div class="avgrating"><div class="star_rating" id="3_2"></div><span class="reviews"> & Up (<span class="BAvg3">'.tep_count_avg_rating(3,$current_category_id).'</span>)</span></div>
	 <div class="avgrating"><div class="star_rating" id="2_2"></div><span class="reviews"> & Up (<span class="BAvg2">'.tep_count_avg_rating(2,$current_category_id).'</span>)</span></div>
	 <div class="avgrating"><div class="star_rating" id="1_2"></div><span class="reviews"> & Up (<span class="BAvg1">'.tep_count_avg_rating(1,$current_category_id).'</span>)</span></div>';
  */
      $data = '<div class="ui-widget infoBoxContainer">' .
                  '  <div class="ui-widget-header infoBoxHeading">' . MODULE_BOXES_BRANDS_BOX_TITLE . '</div>' .
                  '  <div class="ui-widget-content infoBoxContents">' . $content . '
				  <br><br></div>' .
                  '</div>';
     

      return $data;
    }

    function execute() {
      global $SID, $oscTemplate;

      if ((USE_CACHE == 'true') && empty($SID)) {
        $output = tep_cache_manufacturers_box();
      } else {
        $output = $this->getData();
      }

      $oscTemplate->addBlock($output, $this->group);
    }

    function isEnabled() {
      return $this->enabled;
    }

    function check() {
      return defined('MODULE_BOXES_BRANDS_STATUS');
    }

    function install() {
      tep_db_query("insert into " . TABLE_CONFIGURATION . " (configuration_title, configuration_key, configuration_value, configuration_description, configuration_group_id, sort_order, set_function, date_added) values ('Enable Brands Module', 'MODULE_BOXES_BRANDS_STATUS', 'True', 'Do you want to add the module to your shop?', '6', '1', 'tep_cfg_select_option(array(\'True\', \'False\'), ', now())");
      tep_db_query("insert into " . TABLE_CONFIGURATION . " (configuration_title, configuration_key, configuration_value, configuration_description, configuration_group_id, sort_order, set_function, date_added) values ('Content Placement', 'MODULE_BOXES_BRANDS_CONTENT_PLACEMENT', 'Left Column', 'Should the module be loaded in the left or right column?', '6', '1', 'tep_cfg_select_option(array(\'Left Column\', \'Right Column\'), ', now())");
      tep_db_query("insert into " . TABLE_CONFIGURATION . " (configuration_title, configuration_key, configuration_value, configuration_description, configuration_group_id, sort_order, date_added) values ('Sort Order', 'MODULE_BOXES_BRANDS_SORT_ORDER', '0', 'Sort order of display. Lowest is displayed first.', '6', '0', now())");
    }

    function remove() {
      tep_db_query("delete from " . TABLE_CONFIGURATION . " where configuration_key in ('" . implode("', '", $this->keys()) . "')");
    }

    function keys() {
      return array('MODULE_BOXES_BRANDS_STATUS', 'MODULE_BOXES_BRANDS_CONTENT_PLACEMENT', 'MODULE_BOXES_BRANDS_SORT_ORDER');
    }
  }
?>
